//
//  BuyClassesViewController.m
//  jiyujiaProgram
//
//  Created by 中良 赵 on 15/10/13.
//  Copyright (c) 2015年 中良 赵. All rights reserved.
//

#import "BuyClassesViewController.h"
#import "UnpaybillTableViewCell.h"
#import "MyOrderCell.h"
#import "MyOrderModel.h"
#import "Common.h"

@interface BuyClassesViewController ()<UITableViewDelegate,UITableViewDataSource,MyOrderCellDelegate>
{
    VOSegmentedControl *_segment;
    UITableView * _tableView;
    MemberModel *_memberModel;
    TeacherModel *_teacherModel;
    NSMutableArray *_dataArray;
    NSInteger _pageIndex;
    MyOrderModel *_myOrderModel;
    NSString *cancelOrderId;
}
@end

@implementation BuyClassesViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self creatSegmentController];
    [self creatTableView];
    cancelOrderId=@"";
    [self.view bringSubviewToFront:_cancelBillView];
    _cancelBillView.hidden=YES;

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [self loadUserInfo];
    [self segmentClick:_segment];
}

- (void)leftBtnClick:(id)leftSender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)loadUserInfo
{
    UserInfoManager *userInfo = [UserInfoManager sharedUserInfoManager];
    [userInfo loadUserInfoFromSanbox];
    _memberModel = userInfo.memberModel;
    _teacherModel = userInfo.teacherModel;
}


- (void)creatFirstHttpRequest
{
    NSDictionary *param = @{
                            @"member_Id":_memberModel.member_Id,
                            @"promulgator_mark":@"1",
                            @"pageIndex":[NSString stringWithFormat:@"%ld",(long)_pageIndex],
                            @"pageSize":@"10",
                            };
    
    [[HttpManager defaultManager] postRequestToUrl:RequestURL(ORDER_LP) params:param complete:^(BOOL successed, NSDictionary *result) {
        if (successed) {
            [MyOrderModel setupObjectClassInArray:^NSDictionary *{
                return @{
                         @"data":@"MyOrderData",
                         };
            }];
            
            if (_dataArray) {
                if (_tableView.mj_header.isRefreshing) {
                    [_dataArray removeAllObjects];
                }
            }else{
                _dataArray = [[NSMutableArray alloc] init];
            }
            
            _myOrderModel = [[MyOrderModel alloc] init];
            _myOrderModel = [MyOrderModel objectWithKeyValues:result];
            
            [_dataArray addObjectsFromArray:_myOrderModel.data];
            [_tableView reloadData];
            [_tableView.mj_header endRefreshing];
            [_tableView.mj_footer endRefreshing];
        }else{
            [_tableView.mj_header endRefreshing];
            [_tableView.mj_footer endRefreshing];
        }
    }];
}


- (void)creatSecondHttpRequest
{
    NSDictionary *param = @{
                            @"t_member_Id":_memberModel.member_Id,
                            @"promulgator_mark":@"1",
                            @"pageIndex":[NSString stringWithFormat:@"%ld",(long)_pageIndex],
                            @"pageSize":@"10",
                            };
    
    [[HttpManager defaultManager] postRequestToUrl:RequestURL(ORDER_P) params:param complete:^(BOOL successed, NSDictionary *result) {
        if (successed) {
            [MyOrderModel setupObjectClassInArray:^NSDictionary *{
                return @{
                         @"data":@"MyOrderData",
                         };
            }];
            
            if (_dataArray) {
                if (_tableView.mj_header.isRefreshing) {
                    [_dataArray removeAllObjects];
                }
            }else{
                _dataArray = [[NSMutableArray alloc] init];
            }
            
            _myOrderModel = [[MyOrderModel alloc] init];
            _myOrderModel = [MyOrderModel objectWithKeyValues:result];
            
            [_dataArray addObjectsFromArray:_myOrderModel.data];
            [_tableView reloadData];
            [_tableView.mj_header endRefreshing];
            [_tableView.mj_footer endRefreshing];
        }else{
            [_tableView.mj_header endRefreshing];
            [_tableView.mj_footer endRefreshing];
        }
    }];
}

- (void)creatThirdHttpRequest
{
    NSDictionary *param = @{
                            @"t_member_Id":_memberModel.member_Id,
                            @"promulgator_mark":@"1",
                            @"pageIndex":[NSString stringWithFormat:@"%ld",(long)_pageIndex],
                            @"pageSize":@"10",
                            };
    
    [[HttpManager defaultManager] postRequestToUrl:RequestURL(ORDER_C) params:param complete:^(BOOL successed, NSDictionary *result) {
        if (successed) {
            [MyOrderModel setupObjectClassInArray:^NSDictionary *{
                return @{
                         @"data":@"MyOrderData",
                         };
            }];
            
            if (_dataArray) {
                if (_tableView.mj_header.isRefreshing) {
                    [_dataArray removeAllObjects];
                }
            }else{
                _dataArray = [[NSMutableArray alloc] init];
            }
            
            _myOrderModel = [[MyOrderModel alloc] init];
            _myOrderModel = [MyOrderModel objectWithKeyValues:result];
            
            [_dataArray addObjectsFromArray:_myOrderModel.data];
            [_tableView reloadData];
            [_tableView.mj_header endRefreshing];
            [_tableView.mj_footer endRefreshing];
        }else{
            [_tableView.mj_header endRefreshing];
            [_tableView.mj_footer endRefreshing];
        }
    }];
}

- (void)creatFourthHttpRequest
{
    NSDictionary *param = @{
                            @"t_member_Id":_memberModel.member_Id,
                            @"promulgator_mark":@"1",
                            @"pageIndex":[NSString stringWithFormat:@"%ld",_pageIndex],
                            @"pageSize":@"10",
                            };
    
    [[HttpManager defaultManager] postRequestToUrl:RequestURL(ORDER_LC) params:param complete:^(BOOL successed, NSDictionary *result) {
        if (successed) {
            [MyOrderModel setupObjectClassInArray:^NSDictionary *{
                return @{
                         @"data":@"MyOrderData",
                         };
            }];
            
            if (_dataArray) {
                if (_tableView.mj_header.isRefreshing) {
                    [_dataArray removeAllObjects];
                }
            }else{
                _dataArray = [[NSMutableArray alloc] init];
            }
            
            _myOrderModel = [[MyOrderModel alloc] init];
            _myOrderModel = [MyOrderModel objectWithKeyValues:result];
            
            [_dataArray addObjectsFromArray:_myOrderModel.data];
            [_tableView reloadData];
            [_tableView.mj_header endRefreshing];
            [_tableView.mj_footer endRefreshing];
        }else{
            [_tableView.mj_header endRefreshing];
            [_tableView.mj_footer endRefreshing];
        }
    }];
}

- (void)creatSegmentController
{
    _segment = [[VOSegmentedControl alloc] initWithSegments:@[@{
                                                                  @"text":@"待支付"
                                                                  },@{
                                                                  @"text":@"已支付"
                                                                  },@{
                                                                  @"text":@"已取消"
                                                                  },@{
                                                                  @"text":@"待评价"
                                                                  }]];
    _segment.frame = CGRectMake(0, 64, ECSCREEN_W, 40);
    _segment.animationType = VOSegCtrlAnimationTypeSmooth;
    _segment.contentStyle = VOContentStyleTextAlone;
    _segment.indicatorStyle = VOSegCtrlIndicatorStyleBottomLine;
    _segment.allowNoSelection = NO;
    _segment.scrollBounce = NO;
    _segment.selectedTextFont = [UIFont systemFontOfSize:15];
    _segment.selectedIndicatorColor = NAVC_COLOR;
    _segment.textColor = ECCOLOR(0, 0, 0, 1);
    _segment.selectedTextColor = NAVC_COLOR;
    _segment.selectedBackgroundColor = ECCOLOR(255, 255, 255, 1);
    _segment.backgroundColor = ECCOLOR(255, 255, 255, 255);
    _segment.indicatorThickness = 2;
    _segment.indicatorCornerRadius = 15;
    _segment.selectedSegmentIndex = self.index;
    [_segment addTarget:self action:@selector(segmentClick:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:_segment];
}


- (void)segmentClick:(VOSegmentedControl *)segment
{
    [_tableView.mj_header beginRefreshing];
}

- (void)creatTableView
{
    self.automaticallyAdjustsScrollViewInsets = YES;
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 104, ECSCREEN_W, ECSCREEN_H - 104) style:UITableViewStylePlain];
    
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    _tableView.backgroundColor = BG_COLOR;
    _tableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_tableView];
    
    _tableView.tableFooterView = [[UIView alloc]init];
    
    if ([_tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [_tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([_tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [_tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefresh)];
    [self.view addSubview:_tableView];
}

- (void)headerRefresh
{
    _pageIndex = 0;
    switch (_segment.selectedSegmentIndex) {
        case 0:
        {
            [self creatFirstHttpRequest];
        }
            break;
        case 1:
        {
            [self creatSecondHttpRequest];
        }
            break;
        case 2:
        {
            [self creatThirdHttpRequest];
        }
            break;
        case 3:
        {
            [self creatFourthHttpRequest];
        }
            break;
            
            
        default:
            break;
    }
}

- (void)footerRefresh
{
    if (_dataArray.count%10  == 0) {
        _pageIndex++;
        switch (_segment.selectedSegmentIndex) {
            case 0:
            {
                [self creatFirstHttpRequest];
            }
                break;
            case 1:
            {
                [self creatSecondHttpRequest];
            }
                break;
            case 2:
            {
                [self creatThirdHttpRequest];
            }
                break;
            case 3:
            {
                [self creatFourthHttpRequest];
            }
                break;
                
                
            default:
                break;
        }
    }else{
        [_tableView.mj_footer beginRefreshing];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 130.f;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 5.f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ECSCREEN_W, 5)];
    view.backgroundColor = BG_COLOR;
    return view;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *reuseIdentifier = @"myOrderCell";
    MyOrderCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (nil == cell) {
        NSArray *arr = [[NSBundle mainBundle]loadNibNamed:@"MyOrderCell" owner:nil options:nil];
        for (NSObject *obj in arr) {
            if ([obj isKindOfClass:[MyOrderCell class]]) {
                cell = (MyOrderCell *)obj;
                if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
                    [cell setSeparatorInset:UIEdgeInsetsZero];
                }
                if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
                    [cell setLayoutMargins:UIEdgeInsetsZero];
                }
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                break;
            }
        }
    }
    
    [cell setCellWithModel:_dataArray WithIndexPath:indexPath WithSegment:_segment.selectedSegmentIndex];
    MyOrderData *data = _dataArray[indexPath.section];
    [cell.headImage setImageWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:data.mImageUrl]] placeholderImage:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
        cell.headImage.image=image;
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
    }];
    cell.delegate = self;
    return cell;
}


- (void)myOrderCell:(MyOrderCell *)cell commentClick:(UIButton *)comment
{
    NSIndexPath *indexPath = [_tableView indexPathForCell:cell];
    NSLog(@"----%ld----评论",(long)indexPath.section);
    
}
- (void)myOrderCell:(MyOrderCell *)cell payClick:(UIButton *)pay
{
    NSIndexPath *indexPath = [_tableView indexPathForCell:cell];
    NSLog(@"----%ld----付款",(long)indexPath.section);
    
}

- (void)myOrderCell:(MyOrderCell *)cell chatClick:(UIButton *)chat
{
    NSIndexPath *indexPath = [_tableView indexPathForCell:cell];
    NSLog(@"----%ld----聊天",(long)indexPath.section);
}
- (void)myOrderCell:(MyOrderCell *)cell cancelClick:(UIButton *)cancel
{
    NSIndexPath *indexPath = [_tableView indexPathForCell:cell];
    NSLog(@"----%ld----取消订单",(long)indexPath.section);
    
    MyOrderData *data = _dataArray[indexPath.section];
    NSDate *dateNow=[NSDate date];
    NSLog(@"timeSp:%ld create_time====%f",(long)[dateNow timeIntervalSince1970],data.create_time.doubleValue/1000); //时间戳的值
    int secondsCount=(long)[dateNow timeIntervalSince1970]-data.create_time.doubleValue/1000;
    if (secondsCount<86400) {
        _cancelBillView.hidden=NO;
        [_codeView change];
        cancelOrderId=data.order_Id;
    }else{
        SHOW_ALERT(@"取消订单", @"对不起 由于教师备课成本较高，学生只能在提交订单后的24小时内取消", @"返回", nil, nil);
    }

}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)cancelAction:(id)sender {
    if ([[_codeView.changeString lowercaseString] isEqualToString:_tfCode.text]) {
        _tfCode.text=@"";
        if ([cancelOrderId length]) {
            [SVProgressHUD show];
            NSDictionary *param = @{
                                    @"order_status":@"1",
                                    @"order_Id":cancelOrderId
                                    ,
                                    };
            [[HttpManager defaultManager] postRequestToUrl:RequestURL(CANCELORDERS) params:param complete:^(BOOL successed, NSDictionary *result) {
                if (successed) {
                    _cancelBillView.hidden=YES;
                    [SVProgressHUD dismissWithSuccess:@"取消成功"];
                    [_tableView.mj_header beginRefreshing];
                }else{
                    _cancelBillView.hidden=YES;
                    [SVProgressHUD dismissWithSuccess:@"取消失败"];
                    [_tableView.mj_header beginRefreshing];
                }
            }];
        }else{
            [SVProgressHUD dismissWithSuccess:@"取消失败"];
            _cancelBillView.hidden=YES;
        }
    }else{
        SHOW_ALERT(@"提示", @"验证码不正确", @"确认", nil, nil);
    }

}
- (IBAction)hiddenKeyBoard:(id)sender {
    [self.view endEditing:YES];
}

- (IBAction)cancelViewDismissAction:(id)sender {
    _cancelBillView.hidden=YES;
}
@end
